layui.config({
    base : "/js/"
});
layui.use(['form','layer','table','laytpl','commonDeal'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table,
        commonDeal=layui.commonDeal;//自定义公用事件模块
    //自定义公用事件模块启用
    commonDeal.begin();


    //用户列表
    var tableIns = table.render({
        elem: '#userList',
//      url : '../../json/userList.json',
		url : layui.sessionData("bgConfig").backUrl+'/user/getUserListLike',
		request: {
		  pageName: 'current' //页码的参数名称，默认：page
		  ,limitName: 'size' //每页数据量的参数名，默认：limit
		},
		response: {
		  statusName: 'resultType' //数据状态的字段名称，默认：code
		  ,statusCode: 'SUCCESS' //成功的状态码，默认：0
		  ,msgName: 'msg' //状态信息的字段名称，默认：msg
		},
		 done: function(res, curr, count){

		  },
        cellMinWidth : 95,
        page : true,
        height : "full-125",
        limits : [10,15,20,25],
        limit : 20,
        id : "userListTable",
        cols : [[
            {type: "checkbox", fixed:"left", width:50},
            {field: 'account', title: '用户名', minWidth:100, align:"center"},
            {field: 'username', title: '昵称', minWidth:100, align:"center"},
            {field: 'email', title: '用户邮箱', minWidth:200, align:'center'},
            {field: 'valid', title: '用户状态',  align:'center',templet:function(d){
                return d.valid == "0" ? "冻结" : "正常";
            }},
            {field: 'sex', title: '性别', align:'center',templet:function(d) {
                if(d.sex=='MAN'){
                    return "男";
                }else if(d.sex=='WOMAN'){
                    return "女";
                }else if(d.sex=='SECRET'){
                    return "保密";
                }
            }},
            {field: 'phone', title: '手机号', align:'center',minWidth:150},
            {title: '操作', minWidth:175, templet:'#userListBar',fixed:"right",align:"center"}
        ]],
        text: {
		    none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
		}
    });
	//搜索
    $(".search_btn").on("click",function(){
        table.reload("userListTable",{
            where: {
                keyword: $(".searchVal").val()  //搜索的关键字
            }
        })
    });



    //添加用户
    function addUser(edit){
        var index = layui.layer.open({
            title : "添加用户",
            type : 2,
            content : "userAdd.html",
            success : function(layero, index){
                var body = layui.layer.getChildFrame('body', index);
                if(edit){
                    body.find("input[name='id']").val(edit.id);
                    body.find("input[name='version']").val(edit.version);
                    body.find("input[name='account']").val(edit.account);  //登录名
                    body.find("input[name='username']").val(edit.username);  //昵称
                    body.find("input[name='email']").val(edit.email);  //邮箱
                    body.find("input[name='sex'][value='"+edit.sex+"']").prop("checked","checked");  //性别
                    body.find("input[name='phone']").val(edit.phone);  //手机
                    body.find("input[name='userType'][title='"+edit.userType+"']").prop("checked","checked");  //角色
                    if(edit.valid){
                        body.find("input[name='valid']").prop("checked","checked");   
                    }else{
                        body.find("input[name='valid']").removeAttr("checked");
                    }
                    body.find(".password").hide();
                    form.render();
                }else{
                    body.find(".password").show();
                    body.find("input[name='account']").removeAttr("disabled");
                    body.find("input[name='account']").attr("lay-verify","required");
                }
                setTimeout(function(){
                    layui.layer.tips('点击此处返回用户列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        })
        layui.layer.full(index);
        window.sessionStorage.setItem("index",index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            layui.layer.full(window.sessionStorage.getItem("index"));
        })
    }
    $(".addNews_btn").click(function(){
        addUser();
    })

    //批量删除
    $(".delAll_btn").click(function(){
        var checkStatus = table.checkStatus('userListTable'),
            data = checkStatus.data,
            newsId = [];
        if(data.length > 0) {
            for (var i in data) {
                newsId.push(data[i].id);
            }
            layer.confirm('确定删除选中的用户？', {icon: 3, title: '提示信息'}, function (index) {
                $.post(layui.sessionData("bgConfig").backUrl+'/user/userDelete',{userIds:newsId},function(rw){
                    if (rw.resultType == 'SUCCESS') {
                        $(".search_btn").click();
                        layer.close(index);
                    }else{
                        layer.close(index);
                    }
                });
            })
        }else{
            layer.msg("请选择需要删除的用户");
        }
    })

    //列表操作
    table.on('tool(userList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent === 'edit'){ //编辑
            addUser(data);
        }else if(layEvent === 'usable'){ //启用禁用
            var _this = $(this),
                usableText = "是否确定禁用此用户？";
            if(_this.text().indexOf("已禁用") >= 0){
                usableText = "是否确定启用此用户？";
            }
            layer.confirm(usableText,{
                icon: 3,
                title:'系统提示',
                cancel : function(index){
                    layer.close(index);
                }
            },function(index){
                $.post(layui.sessionData("bgConfig").backUrl+'/user/userStatusChange',{userId:data.id,valid:!data.valid},function(rw){
                    if (rw.resultType == 'SUCCESS') {
                        $(".search_btn").click();
                        layer.close(index);
                    }else{
                        layer.close(index);
                    }
                });
            },function(index){
                layer.close(index);
            });
        }else if(layEvent === 'del'){ //删除
            layer.confirm('确定删除此用户？',{icon:3, title:'提示信息'},function(index){
                $.post(layui.sessionData("bgConfig").backUrl+'/user/userDelete',{userIds:data.id},function(rw){
                    if (rw.resultType == 'SUCCESS') {
                        $(".search_btn").click();
                        layer.close(index);
                    }else{
                        layer.close(index);
                    }
                });
            });
        }
    });
})
